/**
 * @Author George.
 * @Date 2018/8/29.
 * @Description: .修改请求
 */

import {
    localStorageSyncServer,
    randomGenerator
} from "./common";
let APP = getApp();
class Http {
    constructor() {
        // localStorageSyncServer.get("Token", 'd1ab92f6910398f65631cf99d37b265a56cbdf3ef23c477dbf2d071fcf58d214df40bb2f605bb8c8d032adcfdc0cd11d')
        // 请求header添加自定项，返回header参数
        this.getHeader = (method, formId) => {
            let [Nonce, Time, Token] = [randomGenerator(6), new Date().getTime(), localStorageSyncServer.get("Token")];
            return {
                "content-type": method == "FORM" ? "application/x-www-form-urlencoded" : "application/json;charset=UTF-8",
                "Token": Token,
                "XY-Agent": JSON.stringify({
                    "app_version": "1.0",
                    "os": localStorageSyncServer.get("os"),
                    "channel": 3
                }),
                "Nonce": Nonce,
                "Time": Time,
                "form_id": formId
            }
        };
        // 根据method，反馈url以及参数
        this.getConfig = (method, url, data) => {
            if (method.toUpperCase() == "GET") {
                if (url.match(/::/g)) {
                    Object.keys(data).map(key => {
                        url = url.replace(`::${key}`, data[key]);
                    });
                    data = ""
                    console.log(url)
                } else {
                    url = url
                    data = data
                }

            } else if (method.toUpperCase() == "QUERY") {
                url = url + "?";
                Object.keys(data).map(key => {
                    if (url.match(/&/g)) {
                        url = url + "&" + key + "=" + data[key];
                    } else {
                        url = url + key + "=" + data[key];
                    }
                });
                data = "";
            }
            if (method == "FORM") {
                method = "POST";
            } else if (method == "QUERY") {
                method = "GET"
            }
            return {
                u: url,
                d: data,
                m: method
            }
        };
        // 缓存request到wx中
        this.storeRequest = (request) => {
            // 默认最多存储五个
            let reqObj = wx.customHttpRecorder || {};
            let keys = Object.keys(reqObj);
            let keyNumber = keys.map(v => +v.substring(2));
            if (keys.length == 5) {
                //     获取最早的删除
                let min = Math.min(...keyNumber);
                delete reqObj["t-" + min]
            }
            reqObj["t-" + new Date().getTime()] = request;
            wx.customHttpRecorder = reqObj;
        };
        //  中断所有请求
        this.httpAbort = () => {
            let httpList = wx.customHttpRecorder;
            Object.keys(httpList).map(v => {
                httpList[v].abort();
            });

        }
        /*
         * 增加相应拦截器
         */
        this.interceptorsResponse = (response) => {
            // 预处理相应的数据
            return new Promise((resolve, reject) => {
                if (response.data.code == 0 || response.data.code == -1) {
                    //由于app对状态0和1的敏感性统一将返回数据状态改为：0->200 -1->500
                    if (response.data.code != -1) response.data.code = 200
                    resolve(response.data, "done")
                } else if (response.data.code == -8) {
                    uni.navigateTo({
                        url: "./login"
                    })
                } else {
                    uni.showToast({
                        title: response.data.message,
                        icon: "none",
                        duration: 3000,
                    })
                    reject(response.data, "done")
                }
            })
        }, (error) => {
            // 错误返回 状态码验证
            return Promise.reject(error)
        };
        this.responseError = (error) => {
            if (error.status == 401) {
                uni.showToast({
                    title: error.info,
                    icon: "none",
                    duration: 3000,
                })
            }
        };
        this.complete = (result) => {
            uni.hideNavigationBarLoading(); //完成停止加载
            uni.stopPullDownRefresh() //停止下拉刷新
        }
    };


    request(method, url, data) {
        if (data) {
            var formId = data.form_id || "";
            if (data.form_id) {
                delete data.form_id
            }
        }
        let header = this.getHeader(method, formId);
        let config = this.getConfig(method, url, data);
        let {
            m,
            u,
            d
        } = config;
        // u = Interceptor.request(u);
        return new Promise((resolve, reject) => {
            let request = uni.request({
                url: u,
                method: m,
                data: d,
                header: header,
                success: (response) => {
                    this.interceptorsResponse(response).then((data) => {
                        resolve(data, "done");
                    });
                },
                fail: (error) => { // 失败
                    this.responseError(error)
                    reject(error);
                },
                complete: (result) => { // 完成
                    this.complete(result);
                }
            });
            this.storeRequest(request);
        });
    }
};

class HttpRequest extends Http {
    constructor(url, data) {
        super(url, data);
    }
    save(url) { // post 方法 {}
        return parameter => this.request("POST", url, parameter)
    }

    get(url) { // get 方法 /{}
        return parameter => this.request("GET", url, parameter)
    }

    query(url) { // get 方法  ? + &
        return parameter => this.request("QUERY", url, parameter)
    }

    form(url) { // get 方法 form{}
        return parameter => this.request("FORM", url, parameter)
    }
}

export default new HttpRequest();